import 'package:bot_toast/bot_toast.dart';
import 'package:dio/dio.dart';
import 'package:wallpaper/http/http_method.dart';

class DioInstance {
  static DioInstance? _instance;

  DioInstance._internal();

  static DioInstance instance() {
    _instance ??= DioInstance._internal();
    return _instance!;
  }

  final Dio _dio = Dio();
  static const Duration _duration = Duration(seconds: 30);

  void initDio({
    String? httpMethod = HttpMethod.GET,
    required String baseUrl,
    Duration? connectTimeout = _duration,
    Duration? receiveTimeout = _duration,
    Duration? sendTimeout = _duration,
    ResponseType? responseType = ResponseType.json,
    String? contentType = Headers.jsonContentType,
    List<Interceptor>? interceptors,
  }) {
    _dio.options = BaseOptions(
      baseUrl: baseUrl,
      method: httpMethod,
      connectTimeout: connectTimeout,
      receiveTimeout: receiveTimeout,
      sendTimeout: sendTimeout,
      responseType: responseType,
      contentType: contentType,
    );

    // 添加拦截器
    if (interceptors != null) {
      for (var interceptor in interceptors) {
        _dio.interceptors.add(interceptor);
      }
    }
  }

  // 添加请求拦截器
  void addTokenInterceptor(String token) {
    _dio.interceptors.add(InterceptorsWrapper(
      onRequest: (RequestOptions options, RequestInterceptorHandler handler) {
        // 添加 Token 到请求头
        options.headers['Authorization'] = 'Bearer $token';
        return handler.next(options);
      },
    ));
  }

  // 添加响应拦截器 response.data.code==500时，提示用户登录过期
  void addResponseInterceptor() {
    _dio.interceptors.add(InterceptorsWrapper(
      onResponse: (Response response, ResponseInterceptorHandler handler) {
        // 处理响应数据
        if (response.data is! Map || !response.data.containsKey('code')) {
          return handler.next(response);
        }
        if (response.data['code'] == 500) {
          // 提示用户登录过期
          BotToast.showText(text: '登录过期，请重新登录');
          // 跳转到登录页面
          // Navigator.pushReplacement(context, MaterialPageRoute(builder: (context) => LoginPage()));
        }
        return handler.next(response);
      },
    ));
  }

  // get请求
  Future<Response> get(
      {required String path,
      Map<String, dynamic>? param,
      Options? options,
      CancelToken? cancelToken}) {
    return _dio.get(path,
        queryParameters: param,
        options: options ??
            Options(
                method: HttpMethod.GET,
                receiveTimeout: _duration,
                sendTimeout: _duration),
        cancelToken: cancelToken);
  }

  // post请求
  Future<Response> post(
      {required String path,
      Object? data,
      Map<String, dynamic>? queryParameters,
      Options? options,
      CancelToken? cancelToken}) {
    return _dio.post(path,
        data: data,
        queryParameters: queryParameters,
        options: options ??
            Options(
                method: HttpMethod.POST,
                receiveTimeout: _duration,
                sendTimeout: _duration),
        cancelToken: cancelToken);
  }
}
